package com.alpha.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpha.bom.RealExam;
import com.alpha.dao.ExamDao;
import com.alpha.dao.ExamResponseDao;

/**
 * Servlet implementation class DeactivateExamServlet
 */
@WebServlet("/DeactivateExamServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class DeactivateExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(DeactivateExamServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeactivateExamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		int examId = 0;
		
		if(request.getParameter("exam_id")!=null){
			try {
				examId = Integer.parseInt(request.getParameter("exam_id"));
			} catch (NumberFormatException e) {
				logger.error(e.getMessage());
				response.sendRedirect("ExamsAdminServlet?error=Exam+not+found.");
				return;
			}
		}
		
		ExamDao eDao = new ExamDao();
		
		try {
			RealExam exam = (RealExam) eDao.retrieveExamById(examId);
			ExamResponseDao erDao = new ExamResponseDao();
			erDao.updateDateTakenOfUntakenExamResponse(exam.getExamId());
			exam.setLocked(true);
			eDao.updateExam(exam);
			if(request.getHeader("Referer").contains("Home.jsp")){
				response.sendRedirect("HomeServlet?success=Exam+deactivated!");
				return;
			} else {
				response.sendRedirect("ExamsAdminServlet?success=Exam+deactivated!");
				return;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			response.sendRedirect("ExamsAdminServlet?error=Exam+not+found.");
			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
